import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberToCarrierMapper;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder;

import java.util.Locale;

public class PhoneUtil {
    private static PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

    private static PhoneNumberToCarrierMapper carrierMapper = PhoneNumberToCarrierMapper.getInstance();

    private static PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();
    private static String LANGUAGE ="CN";

    /**
     * 根据国家代码和手机号  判断手机运营商 例如：江苏省南京市移动
     * @param phoneNumber
     * @return
     */
    public static String getCarrier(String phoneNumber){

        Phonenumber.PhoneNumber referencePhonenumber = new Phonenumber.PhoneNumber();
        try{
            referencePhonenumber = phoneNumberUtil.parse(phoneNumber,LANGUAGE );
            //返回结果只有英文，自己转成成中文
            String carrierEn = carrierMapper.getNameForNumber(referencePhonenumber, Locale.ENGLISH);
            String carrierZh = "";
            carrierZh += geocoder.getDescriptionForNumber(referencePhonenumber, Locale.CHINESE);
            switch (carrierEn) {
                case "China Mobile":
                    carrierZh += "移动";
                    break;
                case "China Unicom":
                    carrierZh += "联通";
                    break;
                case "China Telecom":
                    carrierZh += "电信";
                    break;
                default:
                    break;
            }
            System.out.println();
            if(carrierZh.equals("")){
                return "未知";
            }else {
                return carrierZh;
            }
        }
        catch (NumberParseException e){
            return "未知";
        }


    }


    /**
     *
     * @Description: 根据国家代码和手机号  手机归属地 例如：江苏省南京市
     * @param @param phoneNumber
     * @param @return    参数
     * @throws
     */
    public static String getGeo(String phoneNumber){
        Phonenumber.PhoneNumber referencePhonenumber = null;
        String res="";
        try {
            referencePhonenumber = phoneNumberUtil.parse(phoneNumber, LANGUAGE);
        } catch (NumberParseException e) {

        }
        res=geocoder.getDescriptionForNumber(referencePhonenumber,Locale.CHINA);
        if(res.equals("")){
            return "未知";
        }else {
            return res;
        }

    }

}

